<!-- 商户历史数据 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" :showPanel="false" :showExport="true"
    @changeSize="changeSize" @download="getSearchList('export')" @changePage="changePage" @search="getSearchList"
    @reset="onHideDetails(true)" @changeTh="data.dialogVisible = true" @sort="sortTable" >
    <template #form>
      <el-form-item label="地区：" v-if="!indexStore.is_general_agent">
        <el-select class="formItem500" v-model="data.query.area_s" filterable multiple placeholder="请选择">
          <el-option v-for="(item, index) in COUNTRY" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="货币：" v-if="!indexStore.is_general_agent">
        <el-select class="formItem500" v-model="data.query.currency_ids" filterable multiple placeholder="请选择">
          <el-option v-for="(item, index) in data.currentList" :key="index"
            :label="item.name + ' (' + item.symbol + ')' + '-' + item.remark" :value="item.id" />
        </el-select>
      </el-form-item>
      <Operator ref="OperatorRef" @query="queryItem" />
    </template>
    <template #button></template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
          :sortable="item.sortable ? 'custom' : false" show-overflow-tooltip>
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content>
                {{ item.tips }}
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'operated_id'" #default="scope">
            <div class="flex">
              <div class="marginR2" style="width: 55px;">
                <el-tag v-if="!indexStore.is_general_agent" size="small"
                  :type="selectToLabel(indexStore.operatorArray, scope.row.operated_id, 'currency', 'value') == 1 ? 'danger' : 'warning'"
                  style="font-size:10px;">
                  {{ selectToLabel(indexStore.operatorArray, scope.row.operated_id, 'currency', 'value') == 1 ? '多货币' :
                    '正常总代' }}
                </el-tag>
              </div>
              <span>{{ selectToLabel(indexStore.operatorArray, scope.row.operated_id) }}</span>
            </div>
          </template>
          <template v-if="item.prop == 'agent_id'" #default="scope">
            {{ selectToLabel(indexStore.agentArray, scope.row.agent_id) }}
          </template>
          <template v-if="item.prop == 'agent_area'" #default="scope">
            {{ selectToLabel(COUNTRY, scope.row.agent_area) }}
          </template>
          <template v-if="item.prop == 'bet'" #default="scope">
            <span class="colorText">{{ BigWan(scope.row.bet) }}</span>
          </template>
          <template v-if="item.prop == 'game_income'" #default="scope">
            <span :class="colorClass(scope.row.game_income)">{{ BigWan(scope.row.game_income) }}</span>
          </template>
          <template v-if="item.prop == 'rate'" #default="scope">
            <span :class="colorClass(scope.row.rate)">{{ scope.row.rate }}%</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="100">
        <template #header>
          <el-tooltip effect="dark" content="查看此条记录详情日志描述" placement="top">
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          详情
        </template>
        <template #default="scope">
          <el-button type="success" v-permiss="'/system/destroyManager'" size="small" @click="checkDetails(scope.row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData" />

  <!-- 游戏详情 -->
  <el-dialog v-model="data.isShowDetails" width="60%" title="游戏详情" :close-on-click-modal="false" top="8vh"
    :close-on-press-escape="false" @close="onHideDetails">
    <template #header>
      <p class="box-title mustPass">
        【{{ data.checkedItem.agent_id }}】 {{ selectToLabel(indexStore.agentArray, data.checkedItem.agent_id) }}
        <span style="color: #666666;">{{ data.checkedItem.currency }}</span>
      </p>
    </template>
    <div v-loading="indexStore.moduleLoading" class="dialogMaxMultipleButton">
      <SearchTable :list="data.listDetails" :total="data.totalDetails" :showSet="false" @search="getSearchDetailsList"
        @reset="onHideDetails(true)">
        <template #other>
          <el-tabs v-model="data.queryDetails.game_type" type="card" class="demo-tabs" @tab-change="handleClick">
            <el-tab-pane v-for="item in GAMETYPE" :label="item.label" :name="item.value" />
          </el-tabs>
        </template>
        <template #form>
          <GameItem ref="GameItemRef" @query="queryGame" :gameShow="false"/>
        </template>
        <template #button>
          <div class="statistic flex">
            <p>注单金额： <span class="colorText">{{ BigWan(data.totalFrom.bet) }}</span></p>
            <p>合计输赢：<span :class="colorClass(BigWan(data.totalFrom.game_income))">{{ BigWan(data.totalFrom.game_income) }}</span></p>
            <p>合计RTP：<span :class="colorClass(RtpPercent(data.totalFrom.win, data.totalFrom.bet))">{{ RtpPercent(data.totalFrom.win, data.totalFrom.bet) }}</span></p>
          </div>
        </template>
        <template #table>
          <template v-for="(item, index) in data.fieldDetails" :key="index">
            <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
            :sortable="item.sortable ? true : false" >
              <template v-if="item.prop == 'game_id'" #default="scope">
                <GameHeaderInfo :game_id="scope.row.game_id" />
              </template>
              <template v-if="item.prop == 'bet'" #default="scope">
                <span class="colorText">{{ BigWan(scope.row.bet) }}</span>
              </template>
              <template v-if="item.prop == 'game_income'" #default="scope">
                <span :class="colorClass(scope.row.game_income)">{{ BigWan(scope.row.game_income) }}</span>
              </template>
              <template v-if="item.prop == 'rate'" #default="scope">
                <span :class="colorClass(scope.row.rate)">{{ scope.row.rate }}%</span>
              </template>
            </el-table-column>
          </template>
        </template>
      </SearchTable>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import GameItem, { type GameType } from '@/components/FormItem/GameItem.vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { exportToExcel } from '@/utils/export'
import { selectToLabel, colorClass, ArrayReduce,AgentCurrency,sortObjectArray } from '@/utils/index'
import { GAMETYPE } from '@/config/eunm'
import { COUNTRY } from '@/config/country'
import { BigWan, RtpPercent } from '@/utils/math'
import { getMerchantHistory, getMerchantHistoryDetails } from '@/api/gameReport'
import { getMerchantReportCurrency } from '@/api/instrument'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    operated_id: -1,
    agent_id: -1,
    currency_ids: [],
    area_s: [],
    up_or_down: '',
    order_type: '',
    is_usdt_show: false,
  },
  list: [],
  total: 0,
  fields: [
    { label: '上级渠道', prop: 'operated_id', width: '180', visible: true, tips: '商户的上级代理' },
    { label: '商户昵称', prop: 'agent_id', width: '180', visible: true, tips: '商户的名称' },
    { label: '注单金额', prop: 'bet', width: '', visible: true, sortable: true, tips: '' },
    { label: '注单数', prop: 'bet_count', width: '200', visible: true, sortable: true, tips: '' },
    { label: '游戏输赢', prop: 'game_income', width: '', visible: true, sortable: true, tips: '根据筛选日期内查询商户的输赢情况正为盈利、负为亏损' },
    { label: '登录用户', prop: 'count_login_user', width: '200', visible: true, tips: '' },
    { label: '历史RTP', prop: 'rtp', width: '200', visible: true, tips: '' },
  ],
  dialogVisible: false,
  isShowDetails: false,
  isShowExport: false,
  exportLoading: false,
  checkedItem: {} as any,
  queryDetails: {
    platform: -1,
    agent_id: -1,
    game_type: 1,
  },
  listDetails: [],
  totalDetails: 0,
  fieldDetails: [
    { label: '游戏名称', prop: 'game_id', width: '200', visible: true },
    { label: '注单金额', prop: 'bet', width: '', sortable: true, visible: true },
    { label: '注单数', prop: 'bet_count', width: '', sortable: true, visible: true },
    { label: '游戏输赢', prop: 'game_income', width: '', sortable: true, visible: true },
    { label: '登录用户', prop: 'count_login_user', width: '', visible: true },
    { label: '历史RTP', prop: 'rtp', width: '', visible: true },
  ],
  currentList: [] as any[],
  totalFrom:{
    bet: 0,
    game_income: 0,
    win: 0,
    rtp: 0,
  } as any
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}
// 游戏品牌 + 游戏
const queryGame = (item: GameType) => {
  data.queryDetails.platform = item.platform
}

onMounted(async () => {
  getCurrencyList()
  getSearchList()
})

const getSearchList = async (type?: string) => {
  indexStore.setPageLoading(true)
  let query = JSON.parse(JSON.stringify(data.query));
  query.area_s = query.area_s.join(',')
  query.currency_ids = query.currency_ids.join(',')
  if (type && type == 'export') {
    query.size = 10000
  }
  let res = await getMerchantHistory(query)
  res.data?.list.forEach((item: any) => {
    item.game_income = item.bet - item.win
    item.rtp = RtpPercent(item.win, item.bet)
    item.currency = AgentCurrency(item.agent_id)
  })
  // 导出
  if (type && type == 'export') {
    getExport(res.data)
    return
  }
  data.list = res.data.list
  data.total = res.data.total
}

// 商户使用货币
const getCurrencyList = async () => {
  let res = await getMerchantReportCurrency({});
  data.currentList = res.data
}

// 选择游戏tab
const handleClick = async (value: any) => {
  data.queryDetails.game_type = value
  data.queryDetails.platform = -1
  GameItemRef.value.onHideDetails(-1)
  GameItemRef.value.getGameType(value)
  getSearchDetailsList()
}
// 详情
const checkDetails = async (row: any) => {
  data.isShowDetails = true
  data.checkedItem = row
  getSearchDetailsList()
  nextTick(()=>{
    GameItemRef.value.getGameType(1)
  })
}
const getSearchDetailsList = async () => {
  indexStore.setModuleLoading(true)
  let res = await getMerchantHistoryDetails({
    agent_id: data.checkedItem.agent_id,
    platform: data.queryDetails.platform,
    game_type: data.queryDetails.game_type,
  })
  let bet = [] as number[],game = [] as number[],win = [] as number[];
  res.data?.forEach((item: any) => {
    item.game_income = item.bet - item.win
    item.rtp = RtpPercent(item.win, item.bet)
    // 汇总
    bet.push(item.bet)
    game.push(item.game_income)
    win.push(item.win)
  })
  // 汇总
  data.totalFrom.bet = ArrayReduce(bet)
  data.totalFrom.game_income = ArrayReduce(game)
  data.totalFrom.win = ArrayReduce(win)
  data.listDetails = sortObjectArray(res.data,'game_income','desc')
}

// 排序
const sortTable = async (val: any) => {
  data.query.up_or_down = val.order
  if (val.prop == 'rtp') {
    data.query.order_type = 'win/bet'
  } else {
    data.query.order_type = val.prop
  }
  getSearchList()
}

// 导出
const getExport = async (dataList: any) => {
  let header: string[] = []
  let list: never[][] = []

  data.fields.forEach((item) => {
    header.push(item.label)
  })

  dataList.forEach((item: { [x: string]: any }, index: any) => {
    let arr: never[] = []
    data.fields.forEach((x) => {
      switch (x.prop) {
        case 'operated_id':
          arr.push(selectToLabel(indexStore.operatorArray, item[x.prop]) as never)
          break
        case 'bet':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'game_income':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'agent_id':
          arr.push(selectToLabel(indexStore.agentArray, item[x.prop]) as never)
          break
        case 'rtp':
          arr.push(RtpPercent(item['win'],item['bet']) as never)
          break
        default:
          arr.push(item[x.prop] as never)
          break
      }
    })
    list.push(arr)
  })
  exportToExcel(list, header, '商户历史数据')
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}
const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}
// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const OperatorRef = ref<any>()
const GameItemRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.isShowExport = false
  if (show) {
    if(data.isShowDetails){
      data.queryDetails = {
        platform: -1,
        agent_id: -1,
        game_type: 1,
      }
      GameItemRef.value.onHideDetails(-1)
      getSearchDetailsList()
    }else{
      data.query = {
        page: 1,
        size: 50,
        operated_id: -1,
        agent_id: -1,
        currency_ids: [],
        area_s: [],
        up_or_down: '',
        order_type: '',
        is_usdt_show: false,
      }
      OperatorRef.value.onHideDetails()
      getSearchList()
    }
  }
}
</script>

<style scoped lang="scss">
.formItem500 {
  width: 500px;
}
</style>